package ua.com.fesvlast.hotel.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import ua.com.fesvlast.hotel.model.connectionpool.ConnectionManager;
import ua.com.fesvlast.hotel.model.enteties.Bills;
import ua.com.fesvlast.hotel.model.utils.OrderStatus;

public class BillsDAO {
	
	private static Connection conn =ConnectionManager.getConnection();
	
	public boolean createBill(Bills bill){
		
		String sql="INSERT INTO bills (totalPrice, sendDate, message, discount,orderStatus, orderId) VALUES (?,?,?,?,?,?)";
		boolean flag=true;
		PreparedStatement stmt =null;
		
		try{
			stmt=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS );
			
			stmt.setDouble(1, bill.getTotalPrice());
			stmt.setString(2, bill.getSendDate());
			stmt.setString(3, bill.getMessage());
			stmt.setDouble(4, bill.getDiscount());
			stmt.setString(5, bill.getOrderStatus());
			stmt.setInt(6, bill.getOrderId());
			stmt.executeUpdate();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			flag=false;
		}finally{
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		ConnectionManager.releaseConnection(conn);
		return flag;
	}
	
	public List<Bills> getListBills(OrderStatus status){
		List<Bills> result =null;
		
		String sql="SELECT billId,totalPrice, sendDate, message, discount, orderStatus, orderId FROM bills "
				+"WHERE orderStatus='"+status+"'";
		Statement stmt=null;
		ResultSet rs=null;
		try{
			stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
			rs=stmt.executeQuery(sql);
			result=new ArrayList<Bills>();
			
			while(rs.next()){
				Bills bill =new Bills();
				bill.setBillId(rs.getInt("billId"));
				bill.setDiscount(rs.getDouble("discount"));
				bill.setMessage(rs.getString("message"));
				bill.setOrderId(rs.getInt("orderId"));
				bill.setOrderStatus(rs.getString("orderStatus"));
				bill.setSendDate(rs.getString("sendDate"));
				bill.setTotalPrice(rs.getDouble("totalPrice"));
				
				result.add(bill);
			}
			
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			if(rs !=null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(stmt!=null){
				try {
					stmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		ConnectionManager.releaseConnection(conn);
		return result;
	}

}
